# problem id: 6028
# url: https://leetcode-cn.com/contest/weekly-contest-285/problems/count-collisions-on-a-road/
# state: pass 114/119


class Solution:
    def countCollisions(self, directions: str) -> int:
        length = len(directions)
        speed = []
        for s in directions:
            if s == "R":
                speed.append(1)
            elif s == "L":
                speed.append(-1)
            else:
                speed.append(0)

        count = 0
        sur_cnt = 0
        while True:
            last_speed = speed
            for idx in range(length - 1):
                if speed[idx] == 0 and speed[idx + 1] == 0:
                    continue

                value = speed[idx] * speed[idx + 1]
                if (speed[idx] == 0 and speed[idx + 1] == -1) or (speed[idx] == 1 and speed[idx + 1] == 0):
                    count += 1
                    speed[idx] = 0
                    speed[idx+1] = 0
                elif value == -1 and speed[idx] == 1:
                    count += 2
                    speed[idx] = 0
                    speed[idx+1] = 0
                else:
                    pass

            if last_speed == speed:
                if not self.check_sur_cnt(speed):
                    break

        return count

    @staticmethod
    def check_sur_cnt(speed):
        counter = Counter(speed)
        count_neg_1 = 0
        for idx in range(len(speed)):
            if speed[idx] == -1:
                count_neg_1 += 1
            else:
                break

        length = len(speed)
        count_pos_1 = 0
        for idx in range(len(speed)):
            if speed[length - idx - 1] == 1:
                count_pos_1 += 1
            else:
                break

        if counter[-1] == count_neg_1 and counter[1] == count_pos_1:
            return 0

        return 1